package com.hongbo.widget.test_messenger

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import com.google.android.material.snackbar.Snackbar
import com.hongbo.widget.test_messenger.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding
    private var sayService: Messenger? = null

    private val serviceComm = object : ServiceConnection {
        override fun onServiceConnected(
            name: ComponentName?, service: IBinder?
        ) {
            sayService = Messenger(service)
            binding.content.textView.text = "链接成功"
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            sayService = null
            binding.content.textView.text = "链接失败"
        }

    }

    private val messenger: Messenger = Messenger(object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                Constants.MSG_TYPE_SAY -> {
                    val result = msg.data.getString(Constants.MSG_KEY_DATA) ?: ""
                    Snackbar.make(binding.root, result, Snackbar.LENGTH_SHORT).show()
                }
            }
            super.handleMessage(msg)
        }
    })

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)

        val navController = findNavController(R.id.nav_host_fragment_content_main)
        appBarConfiguration = AppBarConfiguration(navController.graph)
        setupActionBarWithNavController(navController, appBarConfiguration)

        binding.fab.setOnClickListener { view ->
            sayService?.let {
                val message = Message()
                message.what = Constants.MSG_TYPE_SAY
                message.data = Bundle().apply {
                    putString(
                        Constants.MSG_KEY_DATA,
                        "客户端发送的消息111"
                    )
                }
                message.replyTo = messenger
                it.send(message)
            }
        }

        initService()
    }

    override fun onDestroy() {
        unbindService(serviceComm)
        super.onDestroy()
    }

    //绑定同项目远程服务
    private fun initService() {
        bindService(
            Intent(this@MainActivity, SayService::class.java), serviceComm, BIND_AUTO_CREATE
        )
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
}